import { useEventBus, UseEventBusReturn } from '@vueuse/core'
import { onMounted, onUnmounted } from 'vue'
type busType = { name: string; func?: () => any; syncName?: string }
type busEmitType = { syncName: string; value: any }
export function useAsthmaBus(): {
  busDict: any
  addBus: busType
  updateBus: busType
  deleteBus: busType
  busAllEmit: any
} {
  // 存着bus
  const dict: any = {}
  // 存着生成的subscribe 留着清理内存
  const unsubscribeDict: any = {}
  // 一对多时的 key-dictName
  const syncEmit: any = {}

  function addBus(name: string, func?: () => any, syncName?: string): void {
    const bus = useEventBus<string>(name)
    dict[name] = bus
    if (func) {
      const unsubscribe = bus.on(func)
      unsubscribeDict[name] = unsubscribe
    }
    // 设置同步bus，同时会调用syncEmit.key所有bus
    if (syncName) {
      if (syncEmit[syncName]) {
        syncEmit[syncName].push(name)
        syncEmit[syncName].reduce((pre: string[], cur: string) => {
          const b = pre.includes(cur)
          if (b) {
            return pre
          } else {
            pre.push(cur)
            return pre
          }
        }, [])
      } else {
        syncEmit[syncName] = [name]
      }
    }
  }

  function updateBus(name: string, func?: () => any): void {
    if (name && func) {
      const bus = dict[name]
      const unsubscribe = bus.on(func)
      unsubscribeDict[name] = unsubscribe
    }
  }
  function deleteBus(name: string): void {
    if (name) {
      const unsubscribe = unsubscribeDict[name]
      unsubscribe()
      delete dict[name]
      delete unsubscribeDict[name]
    }
  }

  function busAllEmit(syncName: string, value: any): void {
    const array: any[] = syncEmit[syncName]
    array.forEach((name) => {
      dict[name].emit(value)
    })
  }

  onMounted(() => {
    console.log('useAsthmaBus onMounted')
  })
  onUnmounted(() => {
    console.log('useAsthmaBus onUnmounted')
    Object.keys(dict).forEach((key) => {
      deleteBus(key)
    })
  })
  return {
    busDict: dict,
    addBus,
    updateBus,
    deleteBus,
    busAllEmit,
  }
}
